import json
from flask import Flask, request, jsonify

app = Flask(__name__)
DATA_FILE = 'app_kami/data/cards.json'

def load_data():
    with open(DATA_FILE, 'r') as file:
        return json.load(file)

def save_data(data):
    with open(DATA_FILE, 'w') as file:
        json.dump(data, file, indent=4)

@app.route('/cards', methods=['GET'])
def get_cards():
    data = load_data()
    return jsonify(data)

@app.route('/cards', methods=['POST'])
def add_card():
    new_card = request.json
    data = load_data()
    data.append(new_card)
    save_data(data)
    return jsonify({'message': '卡密新增成功'}), 201

@app.route('/cards/<int:card_id>', methods=['DELETE'])
def delete_card(card_id):
    data = load_data()
    data = [card for card in data if card['id'] != card_id]
    save_data(data)
    return jsonify({'message': '卡密删除成功'})

@app.route('/cards/<int:card_id>', methods=['PUT'])
def edit_card(card_id):
    updated_card = request.json
    data = load_data()
    for i, card in enumerate(data):
        if card['id'] == card_id:
            data[i] = updated_card
            break
    save_data(data)
    return jsonify({'message': '卡密编辑成功'})

if __name__ == '__main__':
    app.run(debug=True)